package cn.thoughtworks.school.programCenter.controllers;

import cn.thoughtworks.school.programCenter.annotations.Auth;
import cn.thoughtworks.school.programCenter.entities.Organization;
import cn.thoughtworks.school.programCenter.entities.Program;
import cn.thoughtworks.school.programCenter.entities.User;
import cn.thoughtworks.school.programCenter.exceptions.BusinessException;
import cn.thoughtworks.school.programCenter.services.OrganizationService;
import cn.thoughtworks.school.programCenter.services.ProgramService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

import static org.springframework.http.HttpStatus.OK;

@Controller
@RequestMapping(value = "/api/organizations")
public class OrganizationController {

  @Autowired
  private OrganizationService organizationService;
  @Autowired
  private ProgramService programService;
  @GetMapping("programs")
  public ResponseEntity getProgramsByOrganization(@Auth User current,
                                                  @PageableDefault(page = 1, size = 20, sort = {"id"},
                                                    direction = Sort.Direction.DESC) Pageable pageable) {


    return ResponseEntity.ok(organizationService.getProgramsByOrganizationId(current, pageable));
  }

  @GetMapping(value = "programs/{programId}")
  public ResponseEntity getProgram(@PathVariable("programId") Long programId) throws BusinessException {
    Program program = programService.findById(programId);

    return new ResponseEntity<>(program, OK);
  }

  @GetMapping("programs/workspace")
  public ResponseEntity getWorkspaceByOrganization(@Auth User current,
                                                   @PageableDefault(page = 1, size = 20, sort = {"id"},
                                                     direction = Sort.Direction.DESC) Pageable pageable) {


    return ResponseEntity.ok(organizationService.getWorkspaceByOrganizationId(current, pageable));
  }

  @GetMapping(value = "/users/{userId}")
  public ResponseEntity getOrganizationsByUserId(@PathVariable("userId") Long userId,
                                                 @RequestParam(value = "role",defaultValue ="0"
                                                   ,required = false) String role){
    List<Organization> organization = organizationService.getOrganizationsByUserIdAndRole(userId,role);
    return new ResponseEntity(organization,OK);
  }

}
